'''
Created on May 19, 2009

@author: mkiyer
'''

def connect():
    '''
    establish connection to gene database
    '''
    import sqlalchemy
    import elixir
    engine = sqlalchemy.create_engine("sqlite:///genedb.sqlite")
    elixir.session.bind = engine
    elixir.metadata.bind = engine
    elixir.setup_all()

def find_nearest_regulatable_gene(chrom, loc):
    # imports entities for elixir
    #from veggie.db.genedb import Gene
    #connect()

    from veggie.dbutil import init_db
    init_db("sqlite:///genedb.sqlite", False)

    from sqlalchemy.sql.expression import asc, desc
    from veggie.db.genedb import Gene
        
    # for each gene on the same chromosome
    query = Gene.query.filter_by(chrom=chrom)
    # nearest downstream gene
    downstream_query = query.filter(Gene.strand=='+')
    downstream_query = downstream_query.filter(Gene.txStart >= loc)
    downstream_gene = downstream_query.order_by(asc(Gene.txStart)).first()
    # nearest upstream gene
    upstream_query = query.filter(Gene.strand=='-')
    upstream_query = upstream_query.filter(Gene.txEnd < loc)
    upstream_gene = upstream_query.order_by(desc(Gene.txEnd)).first()


    print upstream_gene, downstream_gene
    
    #for rec in downstream_query.order_by(Gene.txStart):
    #    print rec.geneName, rec.txStart        
    #for rec in Gene.query.filter_by(chrom=chrom):
    #    pass


def find_gene_within_range(chrom, loc, range):
    pass

if __name__ == "__main__":
    find_nearest_regulatable_gene('chr1', 1000000)
